package io.api.modules.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.admin.common.service.impl.CrudServiceImpl;
import cn.hutool.core.util.StrUtil;
import io.api.modules.login.dao.UserEquipmentDao;
import io.api.modules.login.dto.UserEquipmentDTO;
import io.api.modules.login.entity.UserEntity;
import io.api.modules.login.entity.UserEquipmentEntity;
import io.api.modules.login.service.UserEquipmentService;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * 用户设备管理
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-08
 */
@Service
public class UserEquipmentServiceImpl extends CrudServiceImpl<UserEquipmentDao, UserEquipmentEntity, UserEquipmentDTO> implements UserEquipmentService {

    @Override
    public QueryWrapper<UserEquipmentEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<UserEquipmentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
        return wrapper;
    }


    @Override
    public UserEquipmentEntity getByUserId(Long userId) {
        return baseDao.getByUserId(userId);
    }

    @Override
    public UserEquipmentEntity getUserEquipmentEntity(Long userId, String bumber) {
        return baseDao.selectOne(new LambdaQueryWrapper<UserEquipmentEntity>()
                .eq(UserEquipmentEntity::getUserid, userId)
                .eq(UserEquipmentEntity::getBumber, bumber));
    }

    // 判断用户设备是否已授权，查询不到记录就创建
    @Override
    public UserEquipmentEntity check(UserEntity user, String bumber) {
        UserEquipmentEntity userEquipmentEntity = getUserEquipmentEntity(user.getId(), bumber);
        if (Objects.isNull(userEquipmentEntity)) {
            UserEquipmentEntity userEquipment = new UserEquipmentEntity();
            userEquipment.setUserid(user.getId().toString());
            userEquipment.setBumber(bumber);
            userEquipment.setState(0);
            baseDao.insert(userEquipment);
            return userEquipment;
        } else {
            return userEquipmentEntity;
        }
    }
}